'use strict'

process.chdir(__dirname)

const titbit = require('titbit')
const fs = require('fs')

try {
  fs.accessSync('./images')
} catch (err) {
  fs.mkdirSync('./images')
}

const app = new titbit({
  debug: true,
  globalLog: true,
  maxBody: 10000000,
  http2: true,
  cert: './rsa/titbit.cert',
  key: './rsa/titbit_private.key'
})

app.use(async (c, next) => {

  //console.log(c.headers, c.stream)

  await next()
})

app.get('/', async c => {
  c.send('ok')
})

app.post('/upload', async c => {
  let f = c.getFile('image')
  if (!f) {
    return c.status(400).send('image not found')
  }

  let fname = c.helper.makeName(f.filename)

  await c.moveFile(f, `./images/${fname}`)

  c.send(fname)

})

app.post('/image', async c => {

  let flist = c.getFile('image', -1)

  let nameList = []
  let errList = []
  let fname

  for (let f of flist) {
    fname = c.helper.makeName(f.filename)
    try {
      await c.moveFile(f, `./images/${fname}`)
      nameList.push(fname)
    } catch (err) {
      errList.push({
        filename: f.filename,
        errmsg: err.message
      })
    }
  }

  c.send({
    nameList,
    errList
  })
})

app.get('/upload', async c => {
  await c.helper.pipe('./upload2.html', c.reply)
})

app.get('/image/:name', async c => {
  await c.helper.pipe(`./images/${c.param.name}`, c.reply)
})

app.run(1234)
